package org.example.course.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import org.apache.poi.ss.usermodel.Workbook;
import org.example.course.common.DataGridView;
import org.example.course.common.ResultObj;
import org.example.course.common.XmSelect;
import org.example.course.common.utils.FileUtils;
import org.example.course.common.utils.StringUtils;
import org.example.course.domain.Course;
import org.example.course.domain.Graduation;
import org.example.course.dto.CourseModel;
import org.example.course.dto.GraduationModel;
import org.example.course.service.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;

/**
 * @Classname CourseController
 * @Description 课程
 * @Date 2020/5/8 15:56
 * @Created by
 */
@RestController
@RequestMapping("courses")
public class CourseController {

    @Autowired
    private CourseService service;


    /**
     * 分页查询
     *
     * @param courseModel
     * @return
     */
    @RequestMapping(value = "/page", method = RequestMethod.POST)
    public DataGridView page(CourseModel courseModel) {
        DataGridView dataGridView = service.findPage(courseModel);
        return dataGridView;
    }

    /**
     * 创建
     *
     * @param course
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.POST)
    public ResultObj create(Course course) {
        if (course == null) {
            return ResultObj.CREATE_ERROR;
        }
        if (service.create(course)) {
            return ResultObj.CREATE_SUCCESS;
        }
        return ResultObj.CREATE_ERROR;
    }


    /**
     * 更新
     *
     * @param course
     * @return
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public ResultObj update(Course course) {
        if (course == null) {
            return ResultObj.UPDATE_ERROR;
        }
        if (service.update(course)) {
            return ResultObj.UPDATE_SUCCESS;
        }
        return ResultObj.UPDATE_ERROR;
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public ResultObj delete(@PathVariable String id) {
        if (!StringUtils.isNumeric(id)) {
            return ResultObj.COMMON_WARN_ID_SHOULD_INTEGER;
        }
        if (service.delete(id)) {
            return ResultObj.DELETE_SUCCESS;
        }
        return ResultObj.DELETE_ERROR;
    }

    /**
     * 删除与毕业要求从表的关联关系
     *
     * @param graduationId
     * @param courseId
     * @return
     */
    @RequestMapping(value = "/deleteGraduation", method = RequestMethod.DELETE)
    public ResultObj deleteGraduation(String graduationId, String courseId) {
        if (!StringUtils.isNumeric(graduationId) || !StringUtils.isNumeric(courseId)) {
            return ResultObj.COMMON_WARN_ID_SHOULD_INTEGER;
        }
        if (service.deleteGraduation(graduationId, courseId)) {
            return ResultObj.DELETE_SUCCESS;
        }
        return ResultObj.DELETE_ERROR;
    }


    /**
     * 更具课程ID查询已选择毕业要求
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/findGraduation/{id}", method = RequestMethod.GET)
    public DataGridView findGraduation(@PathVariable String id) {
        if (!StringUtils.isNumeric(id)) {
            return new DataGridView();
        }
        DataGridView dataGridView = service.findGraduation(id);
        return dataGridView;
    }


    /**
     * 更具课程ID查询毕业要求详情
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/findDetails/{id}", method = RequestMethod.GET)
    public DataGridView findDetails(@PathVariable String id) {
        if (!StringUtils.isNumeric(id)) {
            return new DataGridView();
        }
        DataGridView dataGridView = service.findDetails(id);
        return dataGridView;
    }


    /**
     * 更具课程ID查询考核环节详情
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/findDetailsCheck/{id}", method = RequestMethod.GET)
    public DataGridView findDetailsCheck(@PathVariable String id) {
        if (!StringUtils.isNumeric(id)) {
            return new DataGridView();
        }
        DataGridView dataGridView = service.findDetailsCheck(id);
        return dataGridView;
    }


    /**
     * 更具课程ID查询考核环节
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/findCheck/{id}", method = RequestMethod.GET)
    public DataGridView findCheck(@PathVariable String id) {
        if (!StringUtils.isNumeric(id)) {
            return new DataGridView();
        }
        DataGridView dataGridView = service.findCheck(id);
        return dataGridView;
    }


    /**
     * 更具课程ID查询未选择的毕业要求
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/graduationSelect/{id}", method = RequestMethod.GET)
    public DataGridView graduationSelect(@PathVariable String id) {
        if (!StringUtils.isNumeric(id)) {
            return new DataGridView();
        }
        DataGridView dataGridView = service.graduationSelect(id);
        return dataGridView;
    }


    /**
     * 更具课程ID查询 每个考核环节的考核与评价标准 表
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/findStandard/{id}", method = RequestMethod.GET)
    public DataGridView findStandard(@PathVariable String id) {
        if (!StringUtils.isNumeric(id)) {
            return new DataGridView();
        }
        DataGridView dataGridView = service.findStandard(id);
        return dataGridView;
    }

    /**
     * 更具课程ID查询 每个考核环节的 情况分析表 文档4-2
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/findAnalyze/{id}", method = RequestMethod.GET)
    public DataGridView findAnalyze(@PathVariable String id) {
        if (!StringUtils.isNumeric(id)) {
            return new DataGridView();
        }
        DataGridView dataGridView = service.findAnalyze(id);
        return dataGridView;
    }


    /**
     * 最终表数据的查询 更具课程ID
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/findConclude/{id}", method = RequestMethod.GET)
    public DataGridView findConclude(@PathVariable String id) {
        if (!StringUtils.isNumeric(id)) {
            return new DataGridView();
        }
        DataGridView dataGridView = service.findConclude(id);
        return dataGridView;
    }


    /**
     * 批量添加课程 毕业要求  关联
     *
     * @param ids
     * @return
     */
    @RequestMapping(value = "/addSelectArr", method = RequestMethod.GET)
    public ResultObj addSelectArr(Integer[] ids, String courseId) {


        try {
            if (null != ids && ids.length > 0 && StringUtils.isNumeric(courseId)) {
                if (service.addSelectArr(ids, courseId)) {
                    return ResultObj.CREATE_SUCCESS;
                }
            } else {
                return ResultObj.DELETE_ID_NULL;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.CREATE_ERROR;
        }

        return ResultObj.CREATE_ERROR;
    }


    /**
     * 导入
     *
     * @param multipartFile
     * @return
     */
    @RequestMapping("/import")
    public ResultObj myImport(@RequestParam("file") MultipartFile multipartFile) throws Exception {
        if (multipartFile.isEmpty()) {
            return ResultObj.NO_FILE;
        }
        ImportParams importParams = new ImportParams();
        //更具导入execl具体情况设置
        //设置标题的行数
        importParams.setTitleRows(1);
        //设置表头的行数
        importParams.setHeadRows(1);


        File file = FileUtils.multipartFileToFile(multipartFile);

        List<CourseModel> courseModels = ExcelImportUtil.importExcel(file, CourseModel.class, importParams);
        file.delete();
        Map<String, List<Graduation>> map = new HashMap<>();

        for (CourseModel courseModel : courseModels) {
            Graduation graduation = new Graduation();
            graduation.setContent(courseModel.getContent());
            graduation.setPower(courseModel.getPower());

            String key = courseModel.getName();
            if (map.containsKey(key)) {
                //根据key 更新list<Graduation>
                List<Graduation> graduationList = map.get(key);
                graduationList.add(graduation);
                map.put(key, graduationList);
            } else {
                //创建一条新map(k,v)
                List<Graduation> list = new ArrayList<>();
                list.add(graduation);
                map.put(key, list);
            }

        }

        for (Map.Entry<String, List<Graduation>> m : map.entrySet()) {
//            System.out.println("key:" + m.getKey() + " value:" + m.getValue());
            //插入课程名 .到课程表
            String name = m.getKey();
            Course insert = service.insert(name);
            List<Graduation> graduations = m.getValue();

            service.insertGraduation(insert.getId(), graduations);
        }
        return ResultObj.OPERATE_SUCCESS;
    }

    /**
     * 写文件到本地 : 服务器 无效
     *
     * @throws Exception
     */
    @RequestMapping(value = "/template", method = RequestMethod.GET)
    public ResultObj template() throws IOException {
        List<CourseModel> list = new ArrayList<>();
        Workbook workerbook = ExcelExportUtil.exportExcel(new ExportParams("课程导入模板", "sheet1"), CourseModel.class, list);
        FileOutputStream fileOutputStream = new FileOutputStream("D://Course.xlsx");
        workerbook.write(fileOutputStream);
        fileOutputStream.close();
        return ResultObj.EXECL_SUCCESS;
    }

}
